package com.faithbj.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.faithbj.common.model.CheckTotal;
import com.faithbj.common.model.Region;
import com.faithbj.common.model.compare.AFMOfficalData;
import com.faithbj.common.model.compare.CivilOfficalData;
import com.faithbj.common.model.compare.HPOfficalData;
import com.faithbj.common.model.compare.IBAOfficalData;
import com.faithbj.common.model.compare.PopulationOfficalData;
import com.faithbj.common.model.compare.SIOfficalData;
import com.faithbj.common.model.compare.TaxOfficalData;
import com.faithbj.common.model.fm.FamilyMember;
import com.faithbj.common.utils.DateUtils;
import com.faithbj.constant.Constant;
import com.faithbj.dao.AFMOfficalDataDao;
import com.faithbj.dao.CheckTotalDao;
import com.faithbj.dao.CivilOfficalDataDao;
import com.faithbj.dao.FamilyMemberDao;
import com.faithbj.dao.HPOfficalDataDao;
import com.faithbj.dao.IBAOfficalDataDao;
import com.faithbj.dao.PSOfficalDataDao;
import com.faithbj.dao.RegionDao;
import com.faithbj.dao.SIOfficalDataDao;
import com.faithbj.dao.TaxOfficalDataDao;
import com.faithbj.service.CompareService;
import com.faithbj.support.vo.CompareRequest;
import com.faithbj.webservice.WebServiceClient;

/**
 * 电子比对Service实现类
 * 
 * @author chen liu
 */
@Service("compareService")
@Transactional
public class CompareServiceImpl implements CompareService {
    @Resource
    private CheckTotalDao checkTotalDao;

    @Resource
    private FamilyMemberDao familyMemberDao;

    @Resource
    private RegionDao regionDao;

    @Resource
    private AFMOfficalDataDao afmOfficalDao;
    
    @Resource
    private CivilOfficalDataDao civilOfficalDao;
    
    @Resource
    private HPOfficalDataDao hpOfficalDataDao;
    
    @Resource
    private IBAOfficalDataDao ibaOfficalDao;
    
    @Resource
    private PSOfficalDataDao psOfficalDao;
    
    @Resource
    private SIOfficalDataDao siOfficalDao;
    
    @Resource
    private TaxOfficalDataDao taxOfficalDao;

    @Override
    public String genearateBatch(Map<String, List<CheckTotal>> batchingMap) {
        Map<String, String> batchNumMap = new HashMap<String, String>();
        if (batchingMap.isEmpty()) {
            return null;
        }

        for (String regionId : batchingMap.keySet()) {
            // 查询某个区当天最大的batchNum
            String maxBatchNum = checkTotalDao.queryMaxBatchNumByRegionId(regionId);

            String maxNum = "0";
            if (StringUtils.hasLength(maxBatchNum)) {
                String date = maxBatchNum.substring(maxBatchNum.length() - 10, maxBatchNum.length() - 2);
                maxNum = maxBatchNum.substring(maxBatchNum.length() - 2);

                if (!date.equals(DateUtils.getCurrentDateString("yyyyMMdd"))) {
                    maxNum = "0";
                }

                if (maxNum.equals("99")) {
                    return new String("区县[" + regionId + "][" + date + "]生成批次数已达上限99，请明天再执行!");
                }
            }

            Region region = regionDao.get(regionId);
            if (region == null) {
                return new String("[" + regionId + "]对应的地区不存在!");
            }

            // 生成批次号
            String batchNum = genBatchNum(maxNum, region.getCode());

            // 更新CheckTotal数据表，更新batched和batch_num
            List<CheckTotal> ctList = batchingMap.get(regionId);
            for (CheckTotal ct : ctList) {
                ct.setBatched(true);
                ct.setBatchNum(batchNum);
                checkTotalDao.saveOrUpdate(ct);
            }
            batchNumMap.put(regionId, batchNum);
        }

        // 构造webservice请求并发送委办
        sendCompareRequest(batchingMap, batchNumMap);
        
        return null;
    }

    public String genBatchNum(String maxNum, String regionCode) {
        String batchNumStr = null;
        Integer batchNumInt = new Integer(maxNum) + 1;
        if (batchNumInt < 10) {
            batchNumStr = "0" + batchNumInt;
        } else {
            batchNumStr = batchNumInt.toString();
        }

        StringBuilder sb = new StringBuilder();
        sb.append(regionCode).append(DateUtils.getCurrentDateString("yyyyMMdd")).append(batchNumStr);
        return sb.toString();
    }

    private void sendCompareRequest(Map<String, List<CheckTotal>> batchingMap, Map<String, String> batchNumMap) {
        // 对每一批进行处理
        for (String regionId : batchingMap.keySet()) {
            // 对一个批次(区)的家庭构造请求对象
            Map<String, List<CompareRequest>> requestMap = new HashMap<String, List<CompareRequest>>();
            for (CheckTotal ct : batchingMap.get(regionId)) {
                // 构造当前家庭的各个部委请求对象并插入到Map中
                List<FamilyMember> familyMembers = familyMemberDao.getFamilyMembersByCheckTotal(ct.getId());
                for (String depNum : Constant.OFFICAL_DEP_MAP.keySet()) {

                    CompareRequest request = new CompareRequest(ct.getBatchNum(), depNum, ct.getFamilyMember()
                            .getName(), ct.getFamilyMember().getIdNumber(), ct.getStartDateApprovedIncome(),
                            ct.getEndDateApprovedIncome(), ct.getId());

                    // 添加该家庭所有申请人成员
                    for (FamilyMember member : familyMembers) {
                        request.addApplicant(member.getName(), member.getIdNumber());
                    }

                    if (requestMap.get(depNum) == null) {
                        List<CompareRequest> requestList = new ArrayList<CompareRequest>();
                        requestList.add(request);
                        requestMap.put(depNum, requestList);
                    } else {
                        requestMap.get(depNum).add(request);
                    }
                }
            }

            // 发送当前批次的webService请求
           WebServiceClient.sendRequest(requestMap);
        }
    }

    @Override
    public void saveOrUpdateAFMOfficalData(AFMOfficalData officalData) {
        afmOfficalDao.saveOrUpdate(officalData);
    }

    @Override
    public void saveOrUpdateCivilOfficalData(CivilOfficalData officalData) {
        civilOfficalDao.saveOrUpdate(officalData);
    }

    @Override
    public void saveOrUpdateHPOfficalData(HPOfficalData officalData) {
        hpOfficalDataDao.saveOrUpdate(officalData);
    }

    @Override
    public void saveOrUpdateIBAOfficalData(IBAOfficalData officalData) {
        ibaOfficalDao.saveOrUpdate(officalData);
    }

    @Override
    public void saveOrUpdatePSOfficalData(PopulationOfficalData officalData) {
        psOfficalDao.saveOrUpdate(officalData);
    }

    @Override
    public void saveOrUpdateSIOfficalData(SIOfficalData officalData) {
        siOfficalDao.saveOrUpdate(officalData);
    }

    @Override
    public void saveOrUpdateTaxOfficalData(TaxOfficalData officalData) {
        taxOfficalDao.saveOrUpdate(officalData);
    }

    @Override
    public List<AFMOfficalData> getAFMOfficalDataForUpdate(String batchNum, String departmentNum,
            String mainApplicantCardId) {
        return afmOfficalDao.queryListForUpdate(batchNum, departmentNum, mainApplicantCardId);
    }

    @Override
    public List<CivilOfficalData> getCivilOfficalDataForUpdate(String batchNum, String departmentNum,
            String mainApplicantCardId) {
        return civilOfficalDao.queryListForUpdate(batchNum, departmentNum, mainApplicantCardId);
    }

    @Override
    public List<HPOfficalData> getHPOfficalDataForUpdate(String batchNum, String departmentNum,
            String mainApplicantCardId) {
        return hpOfficalDataDao.queryListForUpdate(batchNum, departmentNum, mainApplicantCardId);
    }

    @Override
    public List<IBAOfficalData> getIBAOfficalDataForUpdate(String batchNum, String departmentNum,
            String mainApplicantCardId) {
        return ibaOfficalDao.queryListForUpdate(batchNum, departmentNum, mainApplicantCardId);
    }

    @Override
    public List<PopulationOfficalData> getPSOfficalDataForUpdate(String batchNum, String departmentNum,
            String mainApplicantCardId) {
        return psOfficalDao.queryListForUpdate(batchNum, departmentNum, mainApplicantCardId);
    }

    @Override
    public List<SIOfficalData> getSIOfficalDataForUpdate(String batchNum, String departmentNum,
            String mainApplicantCardId) {
        return siOfficalDao.queryListForUpdate(batchNum, departmentNum, mainApplicantCardId);
    }

    @Override
    public List<TaxOfficalData> getTaxOfficalDataForUpdate(String batchNum, String departmentNum,
            String mainApplicantCardId) {
        return taxOfficalDao.queryListForUpdate(batchNum, departmentNum, mainApplicantCardId);
    }

    public static void main(String[] args) {
        CompareServiceImpl cs = new CompareServiceImpl();
        System.out.println(cs.genBatchNum("78", "HP"));
    }
}
